﻿/*
Copyright (c) 2013, Marc Tanti
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the www.marctanti.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using MARIA.level;
using MARIA.program.statement;
using MARIA.level.situation.ended_reason;

namespace MARIA
{
    public partial class Game : Form
    {

        private bool isRunning;
        private Stack<Statement> statementStack;
        
        public Game()
        {
            InitializeComponent();
            statementStack = new Stack<Statement>();
            SetLevel(0);
            isRunning = false;
            MakeEditable();
            situationControl.OnSituationEnded += new level.situation.Situation.SituationEndedHandler(situationControl_OnSituationEnded);
        }

        private void SetLevel(int levelNum)
        {
            if (levelNum > cbxLevels.Items.Count - 1)
            {
                for (int level = cbxLevels.Items.Count; level <= levelNum; level++)
                {
                    cbxLevels.Items.Add("Level " + (level + 1) + ": " + Cache.Instance.Levels[level].Title);
                }
            }

            Level levelToBeSet = Cache.Instance.Levels[levelNum];
            cbxLevels.SelectedIndex = levelNum;
            txtLevelDesc.Text = levelToBeSet.Description;
            programControl.SetLevel(levelToBeSet);
            situationControl.SetLevel(levelToBeSet);
            Text = "MARIA - " + levelToBeSet.Title;
        }

        private void MakeEditable()
        {
            programControl.MakeEditable();
            situationControl.MakeEditable();
            btnStop.Enabled = false;
            cbxLevels.Enabled = true;
            mnuFile.Enabled = true;
        }

        private void MakeUneditable()
        {
            programControl.MakeUneditable();
            situationControl.MakeUneditable();
            btnStop.Enabled = true;
            cbxLevels.Enabled = false;
            mnuFile.Enabled = false;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutBox().Show();
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "MARIA saved data|*.maria";
            dialog.ShowDialog(this);

            if (dialog.FileName != "")
            {
                FileStream f = new FileStream(dialog.FileName, FileMode.Open);
                BinaryFormatter b = new BinaryFormatter();

                try
                {
                    int lastLevelId = (int)b.Deserialize(f);

                    int lastLevelNum = 0;
                    Dictionary<int, Statement> programs = (Dictionary<int, Statement>)b.Deserialize(f);
                    for (int levelNum = 0; levelNum < Cache.Instance.Levels.Length; levelNum++)
                    {
                        Level level = Cache.Instance.Levels[levelNum];

                        foreach (int levelId in programs.Keys)
                        {
                            if (level.ID == levelId)
                            {
                                level.Program = programs[levelId];
                                break;
                            }
                        }
                        if (level.ID == lastLevelId)
                        {
                            lastLevelNum = levelNum;
                        }
                    }

                    cbxLevels.Items.Clear();
                    SetLevel(lastLevelNum);
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not load file. Maybe data is of an outdated version of this program.");
                    Cache.Instance.LoadDefaultLevels();
                    cbxLevels.Items.Clear();
                    SetLevel(0);
                }
                finally
                {
                    f.Close();
                }
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "MARIA saved data|*.maria";
            dialog.ShowDialog(this);

            if (dialog.FileName != "")
            {
                FileStream f = new FileStream(dialog.FileName, FileMode.Create);
                BinaryFormatter b = new BinaryFormatter();
                
                b.Serialize(f, Cache.Instance.Levels[cbxLevels.Items.Count - 1].ID);

                Dictionary<int, Statement> programs = new Dictionary<int, Statement>();
                for (int levelNum = 0; levelNum < cbxLevels.Items.Count; levelNum++)
                {
                    Level level = Cache.Instance.Levels[levelNum];
                    programs[level.ID] = level.Program;
                }
                b.Serialize(f, programs);

                f.Close();
            }
        }

        private void cbxLevels_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetLevel(cbxLevels.SelectedIndex);
        }

        private void ExecuteNextInstruction()
        {
            //Started executing program
            if (!programControl.IsExecuting())
            {
                MakeUneditable();
                programControl.SetExecuting(true);
                situationControl.SetSelectedIndex(0);
                statementStack = null;
            }

            //Started new situation
            if (statementStack == null)
            {
                statementStack = new Stack<Statement>();
                programControl.SetSelectedStatement(programControl.GetProgram());
                statementStack.Push(programControl.GetProgram());
            }

            Statement statement = statementStack.Pop();
            statement.Execute(situationControl.GetRobot(), statementStack);

            if (statementStack != null)
            {
                if (statementStack.Count > 0)
                {
                    programControl.SetSelectedStatement(statementStack.Peek());
                }
                else
                {
                    situationControl.GetSelectedSituation().Lost(SituationLostDueToProgramTerminatedTooSoon.Instance);
                }
            }
        }

        private void StopExecuting()
        {
            situationControl.ReinitializeSituations();
            situationControl.RefreshSituationPic();
            programControl.SetExecuting(false);
            isRunning = false;
            statementStack = null;
            MakeEditable();
        }

        void situationControl_OnSituationEnded(object sender, level.situation.SituationEndedEventArgs args)
        {
            isRunning = false;
            statementStack = null;
            situationControl.RefreshSituationPic();
            if (args.HasLost)
            {
                MessageBox.Show(this, args.ReasonEnded.TextualReason, "You lost", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                StopExecuting();
            }
            if (args.HasWon)
            {
                MessageBox.Show(this, args.ReasonEnded.TextualReason, "You won", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //Won last situation
                if (situationControl.GetSelectedIndex() == situationControl.GetSituationCount() - 1)
                {
                    MessageBox.Show(this, "You won the level!", "You won", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    StopExecuting();

                    //Moving to a new level if this was the greatest level reached
                    if (cbxLevels.SelectedIndex == cbxLevels.Items.Count - 1)
                    {
                        if (cbxLevels.Items.Count - 1 < Cache.Instance.Levels.Length - 1)
                        {
                            SetLevel(cbxLevels.SelectedIndex + 1);
                        }
                        else
                        {
                            MessageBox.Show(this, "You won the game! Now you are ready to get into the awesome world of programming!", "You won", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        SetLevel(cbxLevels.SelectedIndex);
                    }
                }
                //More situations left to win
                else
                {
                    situationControl.SetSelectedIndex(situationControl.GetSelectedIndex() + 1);

                    ExecuteNextInstruction();
                }
            }
        }

        private void btnStep_Click(object sender, EventArgs e)
        {
            ExecuteNextInstruction();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            StopExecuting();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            isRunning = true;
            do
            {
                ExecuteNextInstruction();
            } while (isRunning);
        }
    }
}
